import axios from 'axios'
import { showLoading, hideLoading } from './Loading.js';
axios.interceptors.request.use(
  config => {
    showLoading();
    return config
  },
  err => {
    hideLoading();
    return Promise.reject(err)
  }
);
axios.interceptors.response.use(
  response => {
    hideLoading();
    return response;
  },
  error => {
    hideLoading();
    return error.response;
    //return Promise.reject(error.response.data)   // 返回接口返回的错误信息
  }
);


let base = 'http://192.168.27.110:8888'; // 接口域名
// let base = 'http://10.111.43.55:8888'
export {
  base
}
// let base = 'http://10.111.43.55:8888'
export const request = (url, params, method, isJson) => {
  // let _this = this;
  // console.log(localStorage .getItem('token'))
  return new Promise((resolve,reject) => {
    axios({
      method: method,
      url: `${base}${url}`,
      data: method === 'post' ? params : '',
      timeout: 6000,
      transformRequest: [function(data) {
        if (isJson === 1) {
          // debugger       // 判断是否json格式或者是表单提交形式
          return JSON.stringify(data)
        }
        let ret = '';
        for (let it in data) {
          ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
        }
        return ret // 便于直接取到内部data
      }],
      headers: {
        // 认证和请求方式
        'Content-Type': isJson === 1 ? 'application/json' : 'application/x-www-form-urlencoded',
        // 'authorization': sessionStorage.getItem('principal'),
        'authorization':'admin',
        'token': localStorage.getItem('token')

      },
      params: method === 'get' ? params : '',
    }).then(res => {
      resolve(res.data)
    }).catch(err  =>{
      reject(err.data)
    })
  })
};

// post
export const postRequest = (options) => {
  return request(options.url, options.params, 'post', options.isJson)
};

// uploadFileRequest  图片上传
export const uploadFileRequest = (url, data) => {
  return axios({
    method: 'post',
    url: `${base}${url}`,
    data: data,
    headers: {
      'Content-Type': 'multipart/form-data',
      // 'authorization': sessionStorage.getItem('principal'),
      'token': localStorage.getItem('token'),
      'authorization':'admin'
      // 'token':'740a1d6be9c14292a13811cabb99950b'
    }
  })
};

// get

export const getRequest = (options) => {
  return request(options.url, options.params, 'get', options.isJson)
  // request(url, params,'get',Func,isJson)
};
